# -*- coding: utf-8 -*-
"""
销售业务逻辑层

负责销售相关的业务逻辑处理
"""
import math
from decimal import Decimal
from typing import List, Dict, Any, Optional
from app.repositories.sales_repository import SalesRepository


class SalesService:
    """销售业务逻辑类"""
    
    def __init__(self):
        self.sales_repo = SalesRepository()
    
    def _convert_decimal_to_float(self, data):
        """将Decimal类型转换为float，用于JSON序列化"""
        if isinstance(data, dict):
            return {key: self._convert_decimal_to_float(value) for key, value in data.items()}
        elif isinstance(data, list):
            return [self._convert_decimal_to_float(item) for item in data]
        elif isinstance(data, Decimal):
            return float(data) if data is not None else 0.0
        else:
            return data
    
    def get_goods_sales_statistics(self, goods_id: Optional[str] = None, 
                                 page: int = 1, page_size: int = 10,
                                 start_date: Optional[str] = None,
                                 end_date: Optional[str] = None) -> Dict[str, Any]:
        """获取商品销售统计"""
        # 验证分页参数
        if page <= 0:
            page = 1
        if page_size <= 0 or page_size > 100:
            page_size = 10
        
        try:
            result = self.sales_repo.get_goods_sales_statistics(
                goods_id=goods_id,
                page=page,
                page_size=page_size,
                start_date=start_date,
                end_date=end_date
            )
            
            # 转换Decimal为float
            converted_items = self._convert_decimal_to_float(result["items"])
            
            return {
                "code": 200,
                "message": "success",
                "data": {
                    "total": result["total"],
                    "page": page,
                    "pageSize": page_size,
                    "totalPages": math.ceil(result["total"] / page_size),
                    "list": converted_items
                }
            }
        except Exception as e:
            raise Exception(f"获取商品销售统计失败: {str(e)}")
    
    def get_single_goods_sales_detail(self, goods_id: str) -> Dict[str, Any]:
        """获取单个商品的销售详情"""
        if not goods_id:
            raise ValueError("商品ID不能为空")
        
        try:
            result = self.sales_repo.get_single_goods_sales_detail(goods_id)
            
            if not result:
                return {
                    "code": 200,
                    "message": "该商品暂无销售记录",
                    "data": {
                        "goods_id": goods_id,
                        "sales_details": [],
                        "total_sales_quantity": 0,
                        "total_sales_amount": 0,
                        "total_paid_amount": 0
                    }
                }
            
            # 计算汇总数据
            total_sales_quantity = sum(int(item["total_sales_quantity"] or 0) for item in result)
            total_sales_amount = sum(float(item["total_sales_amount"] or 0) for item in result)
            total_paid_amount = sum(float(item["total_paid_amount"] or 0) for item in result)
            
            # 转换Decimal为float
            converted_result = self._convert_decimal_to_float(result)
            
            return {
                "code": 200,
                "message": "success",
                "data": {
                    "goods_id": goods_id,
                    "goods_name": result[0]["goods_name"] if result else "",
                    "sales_details": converted_result,
                    "total_sales_quantity": total_sales_quantity,
                    "total_sales_amount": float(total_sales_amount),
                    "total_paid_amount": float(total_paid_amount),
                    "specs_count": len(result)
                }
            }
        except Exception as e:
            raise Exception(f"获取商品销售详情失败: {str(e)}")
    
    def get_top_selling_goods(self, limit: int = 10, 
                            start_date: Optional[str] = None,
                            end_date: Optional[str] = None) -> Dict[str, Any]:
        """获取销售量排行榜"""
        if limit <= 0 or limit > 100:
            limit = 10
        
        try:
            result = self.sales_repo.get_top_selling_goods(
                limit=limit,
                start_date=start_date,
                end_date=end_date
            )
            
            # 转换Decimal为float并添加排名
            converted_result = self._convert_decimal_to_float(result)
            for index, item in enumerate(converted_result):
                item["rank"] = index + 1
            
            return {
                "code": 200,
                "message": "success",
                "data": {
                    "ranking": converted_result,
                    "count": len(result),
                    "date_range": {
                        "start_date": start_date,
                        "end_date": end_date
                    }
                }
            }
        except Exception as e:
            raise Exception(f"获取销售排行榜失败: {str(e)}")
    
    def get_sales_summary(self, start_date: Optional[str] = None,
                         end_date: Optional[str] = None) -> Dict[str, Any]:
        """获取销售汇总数据"""
        try:
            result = self.sales_repo.get_sales_summary(
                start_date=start_date,
                end_date=end_date
            )
            
            # 转换Decimal为float
            converted_result = self._convert_decimal_to_float(result)
            
            return {
                "code": 200,
                "message": "success",
                "data": {
                    "summary": converted_result,
                    "date_range": {
                        "start_date": start_date,
                        "end_date": end_date
                    }
                }
            }
        except Exception as e:
            raise Exception(f"获取销售汇总失败: {str(e)}") 